#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>

using namespace std;

int networkDelayTime(vector<vector<int>>& times, int n, int k) {
    vector<vector<int>> f(n + 1, vector<int>(n + 1, 0x3f3f3f3f));
    for (int i = 1; i <= n; i++)    f[i][i] = 0;
    for (auto& p : times)
        f[p[0]][p[1]] = min(f[p[0]][p[1]], p[2]);

    for (int k = 1; k <= n; k++)
        for (int i = 1; i <= n; i++)
            for (int j = 1; j <= n; j++)
                f[i][j] = min(f[i][j], f[i][k] + f[k][j]);

    int res = 0;
    for (int i = 1; i <= n; i++)
        res = max(res, f[k][i]);

    return res == 0x3f3f3f3f ? -1 : res;
}